package com.itcast.demo_one.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.ImageView
import android.widget.TextView
import com.itcast.demo_one.R
import com.itcast.demo_one.model.CityData

class CityAdapter(val cityList: List<CityData>) : BaseAdapter() {
    override fun getCount(): Int {
        return cityList.size
    }

    override fun getItem(position: Int): Any {
        return cityList[position]
    }

    override fun getItemId(position: Int): Long {
        return position.toLong()
    }

    override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
        val view: View
        val holder: ViewHolder
        if (convertView == null) {
            // 如果 convertView 为空，加载布局并创建新的 ViewHolder
            view = LayoutInflater.from(parent?.context).inflate(R.layout.item_city_plus, parent, false)
            holder = ViewHolder(view)
            view.tag = holder
        } else {
            // 否则复用已有的 convertView 和 ViewHolder
            view = convertView
            holder = view.tag as ViewHolder
        }

        // 绑定数据到视图
        val cityData = cityList[position]
        holder.cityIcon.setImageResource(cityData.icon)
        holder.cityText.text = cityData.text
        holder.cityIntro.text = cityData.intro

        return view
    }

    // ViewHolder 内部类用于缓存视图组件
    class ViewHolder(view: View) {
        val cityIcon: ImageView = view.findViewById(R.id.cityIcon)
        val cityText: TextView = view.findViewById(R.id.cityText)
        val cityIntro: TextView = view.findViewById(R.id.cityIntro)
    }
}
